package com.xc.shopping_font.Controller;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xc.shopping_font.common.Result;
import com.xc.shopping_font.entity.Cart;
import com.xc.shopping_font.entity.Goods;
import com.xc.shopping_font.service.CartService;
import com.xc.shopping_font.service.GoodsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;


@RestController
@Slf4j
@RequestMapping("/cart")
public class CartController {

    @Autowired
    CartService cartService;

    @Resource
    GoodsService goodsService;


    @PostMapping("/add")
    public Boolean addCart(@RequestBody Cart cart){

        Long productId = cart.getProductId();

        Long customerId =cart.getCustomerId();

        QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();

            queryWrapper.eq("product_id",productId);
            queryWrapper.eq("customer_id",customerId);

            Cart db = cartService.getOne(queryWrapper);

            if(db !=null){
                db.setQuantity(db.getQuantity() + cart.getQuantity());
                cartService.updateById(db);
                return true;
            }


        Goods goods= goodsService.getById(productId);

       String productName =  goods.getName();

       String goodsImg = goods.getGoodsPic();

       Float newPrice = goods.getNewPrice();

       cart.setProductName(productName);

       cart.setPrice(newPrice);

       cart.setGoodsImg(goodsImg);

           return    cartService.save(cart);
    }

    @GetMapping("/page")
    public IPage<Cart> page(@RequestParam Integer pageNum,@RequestParam Integer pageSize,@RequestParam Integer customerId,
    @RequestParam(defaultValue = "") String uname ){


        log.info("pageNum={},pageSize={},customerId={}",pageNum,pageSize,customerId);

        IPage<Cart> page = new Page<>(pageNum,pageSize);

        QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();

        if(!"".equals(uname)){
            queryWrapper.like("product_name",uname);
        }

        queryWrapper.eq("customer_id",customerId);

        queryWrapper.orderByAsc("id");

        return cartService.page(page,queryWrapper);
    }

    @PostMapping
    public Boolean save(@RequestBody Cart cart){

        cart.setCreateTime(DateUtil.now());

        return cartService.saveOrUpdate(cart);
    }


    @DeleteMapping("/{id}")
    public Boolean deleteById(@PathVariable Integer id){


      return   cartService.removeById(id);
    }






}
